package com.hanthink.system.service.impl.pc;

import java.util.List;

import com.hanthink.common.core.domain.entity.SysUser;
import com.hanthink.common.utils.ip.IpUtils;
import com.hanthink.system.domain.repair.EquipOperLog;
import com.hanthink.system.mapper.task.TaskExecuteMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hanthink.common.core.domain.entity.SysDept;
import com.hanthink.common.core.domain.entity.SysDictData;
import com.hanthink.common.core.domain.model.LoginUser;
import com.hanthink.common.exception.CustomException;
import com.hanthink.common.utils.StringUtils;
import com.hanthink.system.domain.pc.EmEquip;
import com.hanthink.system.domain.pc.EmImage;
import com.hanthink.system.mapper.EmEquipMapper;
import com.hanthink.system.mapper.EmImageMapper;
import com.hanthink.system.mapper.SysDictDataMapper;
import com.hanthink.system.service.ISysDeptService;
import com.hanthink.system.service.impl.SysUserServiceImpl;
import com.hanthink.system.service.pc.IEmEquipService;

/**
 * 设备台账Service业务层处理
 * 
 * @author hanthink
 * @date 2021-01-26
 */
@Service
public class EmEquipServiceImpl implements IEmEquipService {
	private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

	@Autowired
	private EmEquipMapper emEquipMapper;

	@Autowired
	private EmImageMapper emImageMapper;

	@Autowired
	private ISysDeptService deptService;

	@Autowired
	private SysDictDataMapper dictDataMapper;

	@Autowired
	private TaskExecuteMapper taskExecuteMapper;

	/**
	 * 查询设备台账
	 * 
	 * @param id 设备台账ID
	 * @return 设备台账
	 */
	@Override
	public EmEquip selectEmEquipById(Long id) {
		return emEquipMapper.selectEmEquipById(id);
	}

	/**
	 * 查询设备台账列表
	 * 
	 * @param emEquip 设备台账
	 * @return 设备台账
	 */
	@Override
	public List<EmEquip> selectEmEquipList(EmEquip emEquip) {
		return emEquipMapper.selectEmEquipList(emEquip);
	}

	/**
	 * 查询设备是否存在
	 * @param emEquip 设备台账
	 * @return 设备台账
	 */
	@Override
	public int selectEmEquipExist(EmEquip emEquip) {
		return emEquipMapper.selectEmEquipExist(emEquip);
	}


	/**
	 * 新增设备台账
	 * 
	 * @param emEquip 设备台账
	 * @return 结果
	 */
	@Override
	public int insertEmEquip(EmEquip emEquip) {
		// 校验设备在系统中是否存在
		EmEquip queryEmEquip = emEquipMapper.selectEmEquipByCode(emEquip.getName());
		if (queryEmEquip != null) {
			throw new CustomException("设备条码:" + emEquip.getName() + "在系统中已存在，请核实");
		}

		return emEquipMapper.insertEmEquip(emEquip);
	}

	/**
	 * 修改设备台账
	 *
	 * @param emEquip 设备台账
	 * @return 结果
	 */
	@Override
	public int updateEmEquip(EmEquip emEquip) {
		return emEquipMapper.updateEmEquip(emEquip);
	}

	/**
	 * 修改设备台账,记录log
	 *
	 * @param emEquip 设备台账
	 * @return 结果
	 */
	@Override
	public int updateEmEquipNew(EmEquip emEquip, LoginUser loginUser) {
		saveLog(emEquip,loginUser);
		return emEquipMapper.updateEmEquip(emEquip);
	}
	@Override
	public int saveLog(EmEquip emEquip, LoginUser loginUser) {
		// 操作用户ObjectUtils.isNotEmpty(equip)
		SysUser user = loginUser.getUser();
		EquipOperLog equipOperLog = new EquipOperLog();
		equipOperLog.setEqKey(emEquip.getId());
		equipOperLog.setSiteKey(Long.valueOf(emEquip.getSiteKey()));
		equipOperLog.setEquipCode(emEquip.getName());
		equipOperLog.setOperUser(user.getUserName());
		equipOperLog.setOperIp(IpUtils.getHostIp());
		equipOperLog.setStatus(emEquip.getStatus());
		// 插入日志
		return taskExecuteMapper.saveEquipOperLog(equipOperLog);
	}


	@Override
	public int updateEmEquipbymachineid(String machineid,String status)
	{
		return emEquipMapper.updateEmEquipbymachineid(machineid,status);
	}

	/**
	 * 批量删除设备台账
	 * 
	 * @param ids 需要删除的设备台账ID
	 * @return 结果
	 */
	@Override
	public int deleteEmEquipByIds(Long[] ids) {
		for (Long id : ids) {
//			EmEquip dictType = selectEmEquipById(id);

			EmImage emImage = new EmImage();
			emImage.setEqKey(id);
			List<EmImage> list = emImageMapper.selectEmImageList(emImage);
			if (list.size() > 0) {
				for (EmImage image : list) {
					emImageMapper.deleteEmImageById(image.getId());
				}
			}
//			if (emImageMapper.countImageById(dictType.getId()) > 0) {
//				throw new CustomException(String.format("%1$s已存在设备文件不能删除", dictType.getName()));
//			}
		}
		return emEquipMapper.deleteEmEquipByIds(ids);
	}

	/**
	 * 删除设备台账信息
	 * 
	 * @param id 设备台账ID
	 * @return 结果
	 */
	@Override
	public int deleteEmEquipById(Long id) {
		return emEquipMapper.deleteEmEquipById(id);
	}

	/**
	 * 导入数据
	 * 
	 * @param EmEquipList     计划数据列表
	 * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
	 * @param operName        操作用户
	 * @return 结果
	 */
	@Override
	public String importEmEquip(List<EmEquip> emEquipList, Boolean isUpdateSupport, String operName) {
		if (StringUtils.isNull(emEquipList) || emEquipList.size() == 0) {
			throw new CustomException("导入设备台账数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		int currentRowNum = 0;
		for (EmEquip emEquip : emEquipList) {
			currentRowNum++;
			try {

				// 校验数据信息
				if (StringUtils.isEmpty(emEquip.getSiteKey())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据 工厂不能为空");
					continue;
				} else if (StringUtils.isEmpty(emEquip.getName())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备编码不能为空");
					continue;
				} else if (StringUtils.isNull(emEquip.getDesc())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备名称不能为空");
					continue;
				} else if (StringUtils.isEmpty(emEquip.getType()) || !StringUtils.isNumeric(emEquip.getType())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备类型不能为空，请填写主设备或辅助设备");
					continue;
				} else if (StringUtils.isEmpty(emEquip.getStatus()) || !StringUtils.isNumeric(emEquip.getStatus())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备状态不能为空，请填写运行或停机");
					continue;
				} else if (StringUtils.isEmpty(emEquip.getModel())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备型号不能为空");
					continue;

				}

				// 事业部匹配
				SysDept hangame = new SysDept();
				hangame.setDeptName(emEquip.getHangameKey());
				List<SysDept> hangameList = deptService.selectDeptList(hangame);
				if (hangameList.size() == 0) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据事业部信息在系统中不存在，请核实");
					continue;
				}
				emEquip.setHangameKey(hangameList.get(0).getDeptId().toString());
				
				// 工厂匹配
				SysDept dept = new SysDept();
				dept.setParentId(hangameList.get(0).getDeptId());
				dept.setDeptName(emEquip.getSiteKey());
				List<SysDept> deptList = deptService.selectDeptList(dept);
				if (deptList.size() == 0) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据工厂信息在事业部中不存在，请核实");
					continue;
				}
				emEquip.setSiteKey(deptList.get(0).getDeptId().toString());

				// 部门匹配
				dept = new SysDept();
				dept.setParentId(deptList.get(0).getDeptId());
				dept.setDeptName(emEquip.getUseDept());
				deptList = deptService.selectDeptList(dept);
				if (deptList.size() == 0) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据部门信息未在对应工厂维护，请核实");
					continue;
				}
				emEquip.setUseDept(String.valueOf(deptList.get(0).getDeptId()));

				// 车间匹配
				SysDictData sysDictData = new SysDictData();
				sysDictData.setDictType("area_type");
				List<SysDictData> dataList = dictDataMapper.selectDictDataList(sysDictData);
				boolean areaIsExisd = false;
				for (SysDictData sysDict : dataList) {
					if (sysDict.getDictLabel().equals(emEquip.getAreaName())) {
						emEquip.setAreaKey(Long.valueOf(sysDict.getDictValue()));
						areaIsExisd = true;
						break;
					}
				}
				if (!areaIsExisd) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备车间信息在系统数据字典中不存在，请核实");
					continue;
				}

				// 设备编码校验
				EmEquip em = emEquipMapper.selectEmEquipByCode(emEquip.getName());
				if (!StringUtils.isNull(em) && isUpdateSupport) {
					emEquip.setId(em.getId());
					this.updateEmEquip(emEquip);
					successNum++;
					successMsg.append("<br/>" + successNum + "、设备台账 " + emEquip.getName() + " 更新成功");
					continue;
				} else if (!StringUtils.isNull(em) && !isUpdateSupport) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备信息在系统中已存在，请核实");
					continue;
				} else if (StringUtils.isNull(em)) {
					this.insertEmEquip(emEquip);
					successNum++;
					successMsg.append("<br/>" + successNum + "、设备台账 " + emEquip.getName() + " 导入成功");
				}

			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、设备台账" + emEquip.getName() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0)

		{
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new CustomException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}

	@Override
	public String importEmEquipImage(List<EmImage> emEmImageList, Boolean isUpdateSupport, LoginUser loginUser) {

		if (StringUtils.isNull(emEmImageList) || emEmImageList.size() == 0) {
			throw new CustomException("导入设备台账图片数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		int currentRowNum = 0;
		for (EmImage emImage : emEmImageList) {
			currentRowNum++;
			try {
				// 校验数据信息
				if (StringUtils.isEmpty(emImage.getEquipCode())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备编码不能为空");
					continue;
				} else if (StringUtils.isEmpty(emImage.getImageDesc())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据文件描述不能为空");
					continue;
				} else if (StringUtils.isNull(emImage.getImagePath())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据文件路径不能为空");
					continue;
				}

				// 设备编码校验
				EmEquip emEquips = emEquipMapper.selectEmEquipByCode(emImage.getEquipCode());
				if (StringUtils.isNull(emEquips)) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备编码在系统中不存在，请核实");
					continue;
				} else {
					emImage.setEqKey(emEquips.getId());
					emImage.setSiteKey(emEquips.getSiteKey() != null ? Long.valueOf(emEquips.getSiteKey()) : 0L);
				}

				// 图片路径检验
				EmImage emImages = emImageMapper.selectEmImageByPath(emImage.getImagePath());

				if (!StringUtils.isNull(emImages) && isUpdateSupport) {
					emImage.setId(emImages.getId());
					emImageMapper.updateEmImage(emImage);
					successNum++;
					successMsg.append("<br/>" + successNum + "、设备图片 " + emImage.getImagePath() + " 更新成功");
					continue;
				} else if (!StringUtils.isNull(emImages) && !isUpdateSupport) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备图片在系统中已存在，请核实");
					continue;
				} else if (StringUtils.isNull(emImages)) {
					emImage.setImageType("1");
					emImageMapper.insertEmImage(emImage);
					successNum++;
					successMsg.append("<br/>" + successNum + "、设备图片 " + emImage.getImagePath() + " 导入成功");
				}

			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、设备图片" + emImage.getImagePath() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, successNum + "条数据导入成功，" + failureNum + "条数据导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new CustomException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}
}
